package com.example.user.myfirstapp.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.StringRequest;
import com.example.user.myfirstapp.MainActivity;
import com.example.user.myfirstapp.MyApplication;
import com.example.user.myfirstapp.R;
import com.example.user.myfirstapp.activity.GoodsListActivity;
import com.example.user.myfirstapp.activity.SearchActivity;
import com.example.user.myfirstapp.common.Constant;
import com.example.user.myfirstapp.common.ImageHelper;
import com.example.user.myfirstapp.common.LoadingDialog;
import com.example.user.myfirstapp.entity.GoodsType;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by user on 2016/5/18.
 */
public class TypeFragment extends Fragment {
    private View view;
    private ListView lv_type;
    private GridView lv_twoleveltypelist;
    private Button bt_type_search;
    private TextView typename;
    private NetworkImageView right_top_img;
    private Gson gson;
    private List<GoodsType> typeLists,twoLevelTypeLists;
    private ArrayList<HashMap<String, Object>> listItem;
    private MainActivity mainActivity;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view =inflater.inflate(R.layout.flg_type,container,false);

        mainActivity =(MainActivity) getActivity();

        //搜索按钮点击事件
        bt_type_search=(Button)view.findViewById(R.id.bt_type_search);
        bt_type_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent =new Intent(getActivity(), SearchActivity.class);
                startActivity(intent);
            }
        });

        lv_type=(ListView)view.findViewById(R.id.lv_typelist);
        lv_twoleveltypelist=(GridView)view.findViewById(R.id.lv_twoleveltypelist);
        lv_twoleveltypelist.setSelector(new ColorDrawable(Color.TRANSPARENT));//取消GridView点击时出现的黄色背景色
        typename=(TextView)view.findViewById(R.id.tv_typename);
        right_top_img=(NetworkImageView)view.findViewById(R.id.right_top_img);
        listItem=new ArrayList<HashMap<String, Object>>();
        getTypeList();
        return view;
    }

    //获取左侧分类(一级分类)
    private void getTypeList(){
        //显示加载中
        LoadingDialog.showLoading(getActivity(),"请稍后...");


        String url = "http://"+ Constant.host+":"+Constant.port+"/api/GoodsType/GetOnelevelGoodsTypeList/";
        StringRequest request = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        leftTypeBtn(result);
                        //关闭提示语
                        LoadingDialog.closeLoading();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getActivity(), "网络请求失败",
                                Toast.LENGTH_LONG).show();
                        //关闭提示语
                        LoadingDialog.closeLoading();
                }
        });
        request.setTag("get_getTypeList");
        MyApplication.getHttpQueue().add(request);
    }

    //在listvew中显示左侧分类
    private void leftTypeBtn(String json){
        gson = new Gson();
        typeLists=new ArrayList<GoodsType>();
        typeLists = gson.fromJson(json, new TypeToken<List<GoodsType>>(){}.getType());
        if(typeLists!=null&&typeLists.size()>0) {
            for (GoodsType item : typeLists) {
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("Id", item.getId());
                map.put("TypeName", item.getTypeName());
                map.put("TypeImg", item.getTypeImg());
                listItem.add(map);
            }
            //生成适配器的Item和动态数组对应的元素
            SimpleAdapter listItemAdapter = new SimpleAdapter(
                    getActivity(),
                    listItem, //数据源
                    R.layout.typelist_item, //ListItem的XML实现
                    new String[]{"TypeName"},//动态数组与listItem对应的子项
                    new int[]{R.id.typelist_itemTitle}
            );
            //添加并且显示
            lv_type.setAdapter(listItemAdapter);
            //添加点击事件
            lv_type.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    view.setSelected(true);
                    /** 如果这个ListView存在headerView或者footerView的话,
                     * 点击headerView或者footerView，id=-1，
                     *  而position的值会加上headerView的个数
                     */
                    if(id==-1)
                        return;
                    mainActivity.type_left_position=(int)id;
                    int realPosition=(int)id;
                    ListView lv = (ListView)parent;
                    HashMap<String, Object> map = (HashMap<String, Object>) lv.getItemAtPosition(realPosition);
                    //显示加载中
                    LoadingDialog.showLoading(getActivity(),"请稍后...");
                    //显示数据信息
                    showInfo(map);

                }
            });
            //默认选中第一个
            lv_type.post(new Runnable() {
                @Override
                public void run() {
                    int firstId=0;
                    mainActivity.type_left_position=firstId;
                    lv_type.getChildAt(firstId).setSelected(true);
                    HashMap<String, Object> map =  (HashMap<String, Object>)lv_type.getItemAtPosition(firstId);
                    //显示数据信息
                    showInfo(map);
                }
            });
        }
    }

    //显示数据信息
    private void showInfo(HashMap<String, Object> map){
        //分类名
        String typeName = map.get("TypeName").toString();
        //分类id
        int typeId = Integer.parseInt(map.get("Id").toString());
        //图片路径
        String imgUrl="http://"+ Constant.host+":"+Constant.port+map.get("TypeImg").toString();
        //改变右侧文字
        typename.setText(typeName);

        //显示右侧顶部的图片

        ImageHelper.showImageByNetworkImageView(MyApplication.getHttpQueue(), right_top_img, imgUrl);
////下面是用ImageRequest读取
//        ImageRequest imageRequest=new ImageRequest(
//                imgUrl,
//                new Response.Listener<Bitmap>() {
//                    @Override
//                    public void onResponse(Bitmap bitmap) {
//                        right_top_img.setImageBitmap(bitmap);
//                    }
//                },300, 100, Bitmap.Config. ARGB_8888,
//                new Response.ErrorListener() {
//                    @Override
//                    public void onErrorResponse(VolleyError arg0) {
//                        Toast.makeText(getActivity(), "网络请求失败",
//                                Toast.LENGTH_LONG).show();
//                    }
//                }
//        );
//        imageRequest.setTag("getRightTopImg");
//        MyApplication.getHttpQueue().add(imageRequest);


        //显示右侧二级分类列表
        showTwoLevelType(typeId);
    }

    //显示右侧二级分类列表
    private void showTwoLevelType(int fatherTypeId){
        String url = "http://"+ Constant.host+":"+Constant.port+"/api/GoodsType/GetListByFatherTypeId/"+fatherTypeId;
        StringRequest request = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        showTwoLevelTypeList(result);
                        //关闭提示语
                        LoadingDialog.closeLoading();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getActivity(), "网络请求失败",
                                Toast.LENGTH_LONG).show();
                        //关闭提示语
                        LoadingDialog.closeLoading();
                    }
                }
        );
        request.setTag("get_getTwoLevleTypeList");
        MyApplication.getHttpQueue().add(request);
    }

    private void showTwoLevelTypeList(String json){
        gson = new Gson();
        twoLevelTypeLists=new ArrayList<GoodsType>();
        twoLevelTypeLists = gson.fromJson(json,new TypeToken<List<GoodsType>>(){}.getType());
        NetworkImageViewAdapter adapter = new NetworkImageViewAdapter(getActivity());
        lv_twoleveltypelist.setAdapter(adapter);
        //点击事件
        lv_twoleveltypelist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(id==-1)
                    return;
                int realPosition=(int)id;
                GridView gv = (GridView)parent;
                Object object=gv.getItemAtPosition(realPosition);
                GoodsType gt = (GoodsType)object;
                int typeId = gt.getId();
                Intent intent =new Intent(getActivity(),GoodsListActivity.class);
                Bundle bundle=new Bundle();
                bundle.putString("typeId",String.valueOf(typeId));
                intent.putExtras(bundle);
                startActivity(intent);
                //从右往左切换
                getActivity().overridePendingTransition(R.animator.slide_right_in,0);
            }
        });
    }

    private class NetworkImageViewAdapter extends BaseAdapter {
        private LayoutInflater layoutInflater = null;
        class ViewHolder {
            TextView name;
            NetworkImageView image;
        }
        public NetworkImageViewAdapter(Context context)
        {
            layoutInflater = LayoutInflater.from(context);
        }
        @Override
        public int getCount() {
            return twoLevelTypeLists == null ? 0 : twoLevelTypeLists.size();
        }

        @Override
        public Object getItem(int position) {
            return twoLevelTypeLists == null ? null : twoLevelTypeLists.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            String baseUrl="http://"+ Constant.host+":"+Constant.port;
            ViewHolder viewHolder = null;
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = layoutInflater.inflate(R.layout.twoleveltypelist_item, null);
                viewHolder.name = (TextView) convertView.findViewById(R.id.textview_typeName);
                viewHolder.image = (NetworkImageView) convertView.findViewById(R.id.imageview_typeImg);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            GoodsType gt = twoLevelTypeLists.get(position);
            viewHolder.name.setText(gt.getTypeName());
            ImageHelper.showImageByNetworkImageView(MyApplication.getHttpQueue(), viewHolder.image, baseUrl+gt.getTypeImg());
            return convertView;
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        //结束时队列里面注销
        MyApplication.getHttpQueue().cancelAll("get_getTypeList");
        MyApplication.getHttpQueue().cancelAll("get_getTwoLevleTypeList");
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden){
            lv_type.post(new Runnable() {
                @Override
                public void run() {
                    int positon = mainActivity.type_left_position;
                    lv_type.getChildAt(positon).setSelected(true);
                }
            });
        }
    }
}
